<template>
  <div style="margin-top: 2vh">
    <el-row :gutter="20">
      <el-col :span="10" :offset="2">
        <div class="chat-container">
          <!-- 左侧在线用户列表 -->
          <el-card class="user-list">
            <strong>{{ sideTitle }}:</strong>
            <div class="user-list-length">
              <div
                v-for="user in consultantList"
                :key="user.userid"
                @click="checkedConstant(user)"
              >
                <div class="user-card">
                  <div class="avatar-item">
                    <el-avatar class="my-avatar" :src="user.avatar"></el-avatar>
                    <div style="margin-left: 10px; margin-bottom: 0px">
                      {{ user.username }}
                    </div>
                  </div>
                  <div class="my-red-dot">
                    <!-- 显示消息红点的图标或其他内容 -->
                    <span
                      class="notificationDot"
                      v-if="unreadCount(user.userid)"
                    >
                      {{ unreadCount(user.userid) }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </el-card>

          <!-- 右侧聊天框和输入框 -->

          <div class="chat-section">
            <!-- 上半部分聊天框 -->
            <div class="chat-box" ref="chatBox">
              <strong
                class="strong-title"
                style="display: block; text-align: center; font-size: 20px"
                >{{ currentName }}</strong
              >
              <div
                class="message"
                v-for="message in currentMessages"
                style="margin-left: 50px"
              >
                <!-- 我发送的消息 -->
                <div
                  class="right-style my-message"
                  v-if="message.sendId == sendId"
                >
                  <div>
                    <div class="time-div">{{ formatDate(message.time) }}</div>
                  </div>
                  <div style="width: 30vw">
                    <div
                      style="
                        display: flex;
                        font-weight: lighter;
                        margin-right: 1vw;
                        justify-content: flex-end;
                      "
                    >
                      {{ username }}
                    </div>
                    <strong
                      class="message-length send-my-message"
                      style="margin-right: 1vw; font-size: 20px"
                    >
                      {{ message.message }}
                    </strong>
                  </div>

                  <div>
                    <el-avatar class="my-avatar" :src="userAvatar"></el-avatar>
                  </div>
                </div>

                <!-- 我接收的消息 -->
                <div
                  class="my-message"
                  style="width: 35vw"
                  v-else="message.sendId == sendId"
                >
                  <div>
                    <el-avatar
                      class="my-avatar"
                      :src="currentAvatar"
                    ></el-avatar>
                  </div>
                  <div style="margin-left: 1vw; width: 20vw">
                    <div style="display: flex; font-weight: lighter">
                      {{ currentName }}
                    </div>
                    <strong class="message-length" style="font-size: 20px">
                      {{ message.message }}
                    </strong>
                  </div>
                  <div>
                    <div class="time-div">{{ formatDate(message.time) }}</div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 下半部分输入框 -->
            <div class="input-box">
              <el-input
                type="textarea"
                :rows="6"
                placeholder="请输入内容,按下回车(enter)发送消息......"
                v-model="newMessage"
                class="my-input"
                @keydown.enter.native="sendMessage"
              >
              </el-input>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import indexedDBUtils from "@/utils/indexedDBUtils";

export default {
  created() {
    //从本地数据库中读取消息
    this.readIndexedDB();

    //建立WebSocket连接
    this.connectWebsocket();

    //获取咨询师列表
    this.getAllUserByRole();
    //消息划到底部
    this.scrollBottom();
  },
  data() {
    return {
      webSocket: "",
      sendId: localStorage.getItem("userId"), //当前用户的id
      username: localStorage.getItem("userName"), //当前用户的用户名
      userrole: localStorage.getItem("userrole"), //当前用户角色
      userAvatar:
        this.$store.state.ipAddr + "/" + localStorage.getItem("avatar"), //当前用户头像
      currentName: "", //选择的用户名字
      currentCheckUserId: "", //选择的用户id
      currentAvatar: "", //当前选择的用户头像
      consultantList: [], //咨询师列表
      currentMessages: [], //与当前选择的咨询师的消息
      messages: [], //所有消息
      newMessage: "",
    };
  },
  computed: {
    sideTitle() {
      return this.userrole == 1 ? "咨询师列表" : "用户列表";
    },
  },
  methods: {
    //读取indexedDB，获取messages
    async readIndexedDB() {
      try {
        const db = await indexedDBUtils.openDB("MyDatabase");

        const retrievedData = await indexedDBUtils.getDataByKey(
          db,
          "signalChat",
          this.sendId
        );
        console.log("Retrieved data:", retrievedData);
        this.messages = retrievedData.messages;
      } catch (error) {
        console.error("Error:", error);
      }
    },
    //添加数据到IndexedDb中
    async addDataToIndexedDB() {
      try {
        const db = await indexedDBUtils.openDB("MyDatabase");
        const addedDataId = await indexedDBUtils.addData(db, "signalChat", {
          sequenceId: this.sendId,
          messages: this.messages,
        });
        console.log("Added data with ID:", addedDataId);
      } catch (error) {
        console.error("Error:", error);
      }
    },
    //更新indexedDB中的messages
    async updateIndexedDB() {
      try {
        const db = await indexedDBUtils.openDB("MyDatabase");

        // 获取原始数据
        const retrievedData = await indexedDBUtils.getDataByKey(
          db,
          "signalChat",
          this.sendId
        );

        // 修改原始数据
        retrievedData.messages = this.messages;

        // 更新数据到 indexedDB
        await indexedDBUtils.updateDB(db, "signalChat", retrievedData);
        console.log("IndexedDB updated successfully");
      } catch (error) {
        console.error("Error updating IndexedDB:", error);
      }
    },
    //添加或者更新数据
    async addOrUpdateDataToIndexedDB() {
      try {
        const db = await indexedDBUtils.openDB("MyDatabase");

        // 尝试获取数据
        const retrievedData = await indexedDBUtils.getDataByKey(
          db,
          "signalChat",
          this.sendId
        );

        if (retrievedData) {
          // 如果数据存在，执行更新逻辑
          retrievedData.messages = this.messages;
          await indexedDBUtils.updateDB(db, "signalChat", retrievedData);
          console.log("IndexedDB data updated successfully");
        } else {
          // 如果数据不存在，执行添加逻辑
          const addedDataId = await indexedDBUtils.addData(db, "signalChat", {
            sequenceId: this.sendId,
            messages: this.messages,
          });
          console.log("Added data with ID:", addedDataId);
        }
      } catch (error) {
        console.error("Error:", error);
      }
    },

    //发送消息
    sendMessage() {
      if (!this.currentCheckUserId) {
        return;
      }
      if (this.newMessage.trim() !== "") {
        let msg = {
          sendId: this.sendId,
          receiveId: this.currentCheckUserId,
          message: this.newMessage.trim(),
          time: new Date(),
          status: 0,
        };
        this.messages.push(msg);
        this.currentMessages.push(msg);

        this.sendWebSocketMessage(msg);
        this.newMessage = "";
        this.scrollBottom();
        //存储时到本地
        this.addOrUpdateDataToIndexedDB();
      }
    },
    //滚动到底部
    scrollBottom() {
      // 滚动聊天框到底部
      this.$nextTick(() => {
        this.$refs.chatBox.scrollTop = this.$refs.chatBox.scrollHeight;
      });
    },
    //建立WebSocket连接
    connectWebsocket() {
      let websocket;
      if (typeof WebSocket === "undefined") {
        console.log("您的浏览器不支持WebSocket");
        Message.error("您的浏览器不支持WebSocket");
        return;
      } else {
        let protocol = "ws";
        let url = "";
        if (window.location.protocol === "https:") {
          protocol = "wss";
        }
        // const token = getToken()
        // if (token == null) {
        //   console.log('token为空不能建立WebSocket连接')
        //   return
        // }

        url =
          protocol +
          "://" +
          this.$store.getters.getServerIp +
          "/websocket/" +
          localStorage.getItem("userId");

        // 打开一个websocket
        websocket = new WebSocket(url);

        this.webSocket = websocket;

        // 建立连接
        websocket.onopen = () => {
          // 发送数据
          // websocket.send('发送数据')
          console.log("websocket连接成功");
        };

        // 客户端接收服务端返回的数据
        websocket.onmessage = (evt) => {
          console.log("websocket返回的数据：", evt);
          let message = JSON.parse(evt.data);

          //正在聊天
          if (this.currentCheckUserId == message.sendId) {
            message.status = 1;
            this.currentMessages.push(message);
            this.scrollBottom();
          }
          this.messages.push(message);
          //缓存到本地数据库
          this.addOrUpdateDataToIndexedDB();
        };
        // 发生错误时
        websocket.onerror = (evt) => {
          console.log("websocket错误：", evt);
        };
        // 关闭连接
        websocket.onclose = (evt) => {
          console.log("websocket关闭：", evt);
        };
      }
    },
    //发送消息到服务器
    sendWebSocketMessage(message) {
      // 获取WebSocket对象
      const websocket = this.webSocket;

      // 检查WebSocket是否已连接
      if (websocket.readyState === WebSocket.OPEN) {
        // 将消息对象转换为JSON字符串并发送
        const jsonMessage = JSON.stringify({ text: message });
        websocket.send(JSON.stringify(message));
      } else {
        console.error("WebSocket连接未打开！");
      }
    },
    //获取角色列表
    getAllUserByRole() {
      let userrole = this.userrole == 1 ? 2 : 1;

      this.$request.getHttp({
        url: "/user/getAllUserByRole",
        params: {
          userrole: userrole,
        },
        success: (data) => {
          if (data.code == 200) {
            let filteredList = data.list.map((item) => {
              // 在此添加处理逻辑，例如，假设要对属性值进行转换
              item.avatar = this.$store.state.ipAddr + "/" + item.avatar;
              return item;
            });

            this.consultantList = filteredList;
          }
        },
        error: (error) => {},
      });
    },
    //选择咨询师
    checkedConstant(constant) {
      //设置选择的咨询师，名字
      this.currentName = constant.username;
      this.currentCheckUserId = constant.userid;
      this.currentAvatar = constant.avatar;

      //得到当前咨询师的消息列表
      this.currentMessages = this.messages.filter((item) => {
        // 在此添加过滤条件，例如，假设要过滤出属性值为 'someValue' 的项
        return (
          (item.sendId == constant.userid && item.receiveId == this.sendId) ||
          (item.sendId == this.sendId && item.receiveId == constant.userid)
        );
      });

      this.clearUnreadMessages(constant.userid);
      this.scrollBottom();

      console.log(this.currentMessages);
    },
    //根据message.sendId计算未读消息数量
    unreadCount(sendId) {
      const count = this.messages.filter((message) => {
        return message.sendId == sendId && message.status === 0;
      }).length;
      return count;
    },
    //已读，清除未读消息
    clearUnreadMessages(sendId) {
      // 遍历 messages，找到符合条件的子项并将其 status 置为1
      this.messages.forEach((message) => {
        if (message.sendId === sendId && message.status === 0) {
          message.status = 1;
        }
      });

      //更新本地数据库
      this.addOrUpdateDataToIndexedDB();
    },
    //格式化时间
    formatDate(date) {
      if (typeof date === "number" || typeof date === "string") {
        // 如果 date 是时间戳或字符串，将其转换为 Date 对象
        date = new Date(date);
      }

      if (!(date instanceof Date) || isNaN(date.getTime())) {
        // 检查是否成功转换为有效的 Date 对象，如果不是，返回空字符串或其他错误处理方式
        return "";
      }

      // 获取当前时间
      const now = new Date();

      // 计算时间差（单位：毫秒）
      const timeDiff = now.getTime() - date.getTime();

      if (timeDiff < 24 * 60 * 60 * 1000) {
        // 如果距离今天不足一天，只显示时分秒
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");
        const seconds = String(date.getSeconds()).padStart(2, "0");

        return `${hours}:${minutes}:${seconds}`;
      } else {
        // 如果距离超过一天，只显示年月日
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");

        return `${year}-${month}-${day}`;
      }
    },
  },
};
</script>

<style scoped>
.chat-container {
  display: flex;
  width: 80vw;
  height: 80vh;
}

.user-list {
  border: 1px solid #ccc;
  padding: 10px;
  width: 15vw;
  height: 80vh;
}

.user-list-length {
  height: 74vh;
  overflow-y: scroll;
}

/* 隐藏滚动条 */
.user-list-length::-webkit-scrollbar {
  width: 0.5em; /* 调整滚动条的宽度 */
}

.user-list-length::-webkit-scrollbar-thumb {
  background-color: transparent; /* 设置滚动条滑块的颜色为透明 */
}

.user-list-length::-webkit-scrollbar-track {
  background-color: transparent; /* 设置滚动条轨道的颜色为透明 */
}

.strong-title {
  position: sticky;
  top: 0;
  background-color: #fff; /* 设置背景颜色，确保文本可见 */
  z-index: 1; /* 设置一个较高的z-index，确保位于其他元素之上 */
  width: 100%; /* 使其占据父容器的整个宽度 */
  display: block; /* 确保元素以块级形式显示 */
  text-align: center; /* 文本居中 */
  font-size: 20px; /* 设置字体大小 */
  padding-top: 1vh;
}

.user-card {
  margin: 10px 0px 10px 5px;
  display: flex;
  align-items: center;
  height: 8vh;
  width: 25vh;
  cursor: pointer;
  transition: box-shadow 0.3s ease; /* 添加过渡效果，使阴影变化更平滑 */
}

.avatar-item {
  display: flex;
  align-items: center;
  margin: 10px 0px 10px 5px;
  width: 10vw;
}
.user-card:hover {
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5); /* 鼠标悬浮时显示阴影，可以根据需要调整阴影的样式 */
}

.user-list div {
  margin-bottom: 5px;
}

.chat-section {
  flex: 1;
  padding-left: 10px;
  display: flex;
  flex-direction: column;
  width: 45vw;
  height: 80vh;
}

.chat-box {
  flex: 1;
  overflow-y: auto;
  border: 1px solid #ccc;
  height: 30vh;
}

.my-message {
  display: flex;
  align-items: center;
  margin-top: 3vh;
  width: 60vh;
}

.right-style {
  margin-left: 23vw;
}

.message {
  margin-bottom: 1vh;
  width: 50vw;
}
.message-length {
  width: 15vw;
}
.time-div {
  margin-top: 5vh;
  display: flex;
  align-items: flex-end;
  justify-content: center;
  height: 5vh;
  width: 12vw;
}
.send-my-message {
  display: flex;
  justify-content: flex-end; /* 更稳定的写法 */
}

.my-avatar {
  width: 3vw;
  height: 3vw;
}

.input-box {
  margin-top: 10px;
  height: 20vh;
}

input {
  padding: 5px;
  margin-right: 5px;
}

.my-input {
  height: 22vh;
  font-size: 20px;
}
button {
  padding: 5px 10px;
}

.my-red-dot {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: flex-end;
}

.notificationDot {
  width: 25px; /* 调整宽度以适应消息数字 */
  height: 25px; /* 调整高度以适应消息数字 */
  background-color: #f74c31;
  border-radius: 50%;
  color: white;
  font-size: 12px; /* 调整字体大小 */
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
